import { Directive, OnInit, OnDestroy, NgZone, Self, ElementRef, Input } from '@angular/core';
import { BroadcastService } from '../../core/service/broadcast.service';
import { DxDataGridComponent } from 'devextreme-angular/ui/data-grid';
import { Subscription } from 'rxjs';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: 'dx-data-gridss'
})
export class DataGridRepaintDirective<B> implements OnInit, OnDestroy {

  @Input() disabledRepaintCheck = false;

  private willRepaint = false;
  private subscription: Subscription;

  constructor(
    private broadcastService: BroadcastService<B>,
    private ngZone: NgZone,
    private eleRef: ElementRef,
    @Self() private dataGrid: DxDataGridComponent
  ) { }

  ngOnInit(): void {
    if (this.disabledRepaintCheck) {
      return;
    }

    this.ngZone.runOutsideAngular(() => {
      window.addEventListener('resize', this.onResize);

      this.subscription = this.broadcastService.subscribe(<any>'ReuseOnInit', () => {
        if (!this.dataGrid.pager.visible && !this.dataGrid.paging.enabled) {
          return;
        }

        Promise.resolve().then(() => {
          const ele = this.eleRef.nativeElement;
          if (this.willRepaint && ele.ownerDocument.contains(ele)) {
            this.dataGrid.instance.repaint();
            this.willRepaint = false;
          }
        });
      });
    });
  }

  onResize = () => {
    this.willRepaint = true;
  }

  ngOnDestroy(): void {
    window.removeEventListener('resize', this.onResize);
    this.subscription.unsubscribe();
  }
}
